package com.lq.learningTest.File;

import java.io.*;

public class DeepCopyUtil {
    public static <T> T deepCopy(T object) throws IOException, ClassNotFoundException {

        //将对象写到字节数组中
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);

        //获取字节数组
        byte[] byteArray = byteArrayOutputStream.toByteArray();

        //反序列化用输入流读出来
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Object o = objectInputStream.readObject();

        //关闭所有开启的流
        byteArrayOutputStream.close();
        objectOutputStream.close();
        byteArrayInputStream.close();
        objectInputStream.close();

        return (T) o;
    }
}
